package cn.liyunqi.ttv.web.service.impl;


import cn.liyunqi.core.exception.BizException;
import cn.liyunqi.core.util.*;
import cn.liyunqi.ttv.web.bo.MailLogInfo;
import cn.liyunqi.ttv.web.bo.UserInfo;
import cn.liyunqi.ttv.web.mapper.DictionaryMapper;
import cn.liyunqi.ttv.web.mapper.MailLogInfoMapper;
import cn.liyunqi.ttv.web.mapper.UserInfoMapper;
import cn.liyunqi.ttv.web.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by win7 on 2017/11/2.
 */
@Transactional
@Service("mailService")
public class MailServiceImpl  implements MailService {

    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Autowired
    private MailLogInfoMapper mailLogInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public void sendMail(Integer type, String mail) throws BizException {

        String host = dictionaryMapper.getValue(DictionaryMapper.MAILSMTPHOST,DictionaryMapper.MAIL);
        String password = dictionaryMapper.getValue(DictionaryMapper.MAILPASSWORD,DictionaryMapper.MAIL);
        String port = dictionaryMapper.getValue(DictionaryMapper.MAILSMTPPORT,DictionaryMapper.MAIL);
        String fromMail = dictionaryMapper.getValue(DictionaryMapper.MAILUSER,DictionaryMapper.MAIL);

        if(StringUtil.isEmptyOrNull(host)
                || StringUtil.isEmptyOrNull(password)
                ||StringUtil.isEmptyOrNull(port)
                || StringUtil.isEmptyOrNull(fromMail)){
            throw new BizException("系统配置有误");
        }

        if(MailService.REGISTER_CODE == type){
            UserInfo temp = userInfoMapper.selectUserInfoByMail(mail);
            if(temp != null){
                throw new BizException("用户已经存在了");
            }
        }


        String value = RandomUtil.getRandomValue(6);
        Long nowTime = TimeUtil.getTime();
        String text = "验证码：" + value + "<br/>发送时间：" + TimeUtil.formatToStringDate(nowTime) + "<br/>请注意，该验证码五分钟内有效！";
        SendMailUtil.sendMail(fromMail,mail,password,text,"www.liyunqi.cn网站验证码",host,port);
        MailLogInfo bo = new MailLogInfo();
        bo.setId(UUIDUtil.getUUID());
        bo.setContent(text);
        bo.setCreateTime(nowTime);
        bo.setKeyCode(value);
        bo.setIsUse(0);
        bo.setType(type);
        bo.setMail(mail);
        mailLogInfoMapper.insert(bo);
    }

}
